<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-checkbox v-model="isFeed" border size="small">投料模式</el-checkbox>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :clearable="false" :option-list="workshopList" placeholder="区域" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<div class="search-bar-item-size2 item-gap">
						<el-date-picker v-model="searchParams.yearMonth" :clearable="false" size="small" style="width: 100%;" type="month" value-format="yyyy-MM" placeholder="月" />
					</div>
					<!--<jk-search-input v-model="searchParams.productionLineNameOrCode" @on-enter="onSearchBtn" :clearable="false" placeholder="产线编号或名称" class="search-bar-item-size2 margin-5-0 item-gap"></jk-search-input>-->
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<el-table
				ref="jkTb"
				v-loading="tableLoading"
				:data="tableData"
				style="width: 100%"
				:height="tableHeight + 20"
				size="mini"
				:highlight-current-row="false"
				:cell-style="tableRowClassName"
				:header-cell-style="tableRowClassName"
			>
				<el-table-column prop="belongDate" label="日期" fixed="left" align="center" width="96"></el-table-column>
				<el-table-column
					v-for="(item, index) in tableHeader"
					:key="index"
					:prop="item.key"
					:label="item.title"
					:width="item.key === 'belongDate' ? 100 : ''"
					:align="['belongDate', 'lineName', '1-2#', '3#', '4#', '5#', '6#'].includes(item.key) ? 'center': 'right'"
				>
					<el-table-column
						v-for="(childItem, childIndex) in item.children"
						:key="childIndex"
						:prop="childItem.key"
						:label="childItem.title"
						:align="childItem.title === '清花' ? 'center' : 'right'"
						:width="childItem.title === '清花' ? '540px' : '80px'"
					>
						<template slot="header">
							<div v-if="childItem.title === '清花'">
								<span class="text-center">清花</span>
								<el-table :header-cell-style="(e) => tableRowClassName({ column: {property: childItem.key} }, e)" :show-header="true" :border="true" :data="[]" :height="38" style="width: 100%" size="mini">
									<el-table-column prop="feedstockDateTime" label="时间" width="150"></el-table-column>
									<el-table-column prop="productName" label="品种" min-width="190"></el-table-column>
									<el-table-column prop="totalWeight" label="投料重量" align="right"></el-table-column>
									<el-table-column prop="elapsedTime" label="距离上次" align="right"></el-table-column>
								</el-table>
							</div>
						</template>

						<template slot-scope="scope">
							<div v-if="childItem.title === '清花'">
								<el-button v-if="isFeed" icon="el-icon-s-cooperation" class="margin-bottom-4" size="mini" @click="onAddBtn(scope, item.key)">投料</el-button>
								<!--<el-button class="margin-bottom-4" size="mini" @click="onDetailBtn(scope, item.key)">{{ scope.row[childItem.key] }}</el-button>-->
								<el-table :show-header="false" :show-summary="true" :border="true" :data="scope.row[`${item.key}qhFeedMaterialList`]" style="width: 100%" size="mini">
									<el-table-column prop="feedstockDateTime" label="时间" width="150"></el-table-column>
									<el-table-column prop="productName" label="品种" min-width="190"></el-table-column>
									<el-table-column prop="totalWeight" label="投料重量" align="right"></el-table-column>
									<el-table-column prop="elapsedTime" label="距离上次" align="right">
										<template slot-scope="scope2">
											<span>{{ scope2.row.elapsedTime }} h</span>
										</template>
									</el-table-column>
								</el-table>
							</div>
							<span v-else>{{ scope.row[childItem.key] }}</span>
						</template>
					</el-table-column>
				</el-table-column>
			</el-table>
			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="searchParams.count"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<detail-dialog
			:data-item="dataItem"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChange"
		></detail-dialog>
		<save-dialog
			:data-params="saveParams"
			:dialog-state="feedMaterialDialogState"
			@on-visible-change="onVisibleChangeOfFeedMaterial"
			@on-finish="onFinishBtnOfFeedMaterial"
		></save-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, formatMonth } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { productionLineMonthData } from '../../../api/production/frontGroupYieldStatistics';
    import detailDialog from './detail-dialog';
    import { ppfProductionLinePage } from '../../../api/production/produtionLine';
    import saveDialog from './save-dialog';

    export default {
        name: 'ProductionLineMonthReport',
        components: {
            saveDialog,
            detailDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                apiItem: {
                    'page': productionLineMonthData
                },
                prefix: 'production:prdOrder',
                isFeed: false,
                feedMaterialDialogState: false,
                detailDialogState: false,
                processList: [
                    { key: 'qhOutputKg', title: '清花' },
                    { key: 'smOutputKg', title: '梳棉' },
                    { key: 'tbOutputKg', title: '头并' },
                    { key: 'mbOutputKg', title: '末并' },
                    { key: 'csOutputKg', title: '粗纱' }
                ],
                tableHeader: [
                    /** { // 格式
                        key: '1-2#',
                        title: '1~2线',
                        children: [
                            { key: '1-2#qhOutputKg', title: '清花' },
                            { key: '1-2#smOutputKg', title: '梳棉' },
                            { key: '1-2#tbOutputKg', title: '头并' },
                            { key: '1-2#mbOutputKg', title: '末并' },
                            { key: '1-2#csOutputKg', title: '粗纱' }
                        ]
                    }*/
                ],
                tableData: [],
                dataId: null,
                workshopList: [],
                tableLoading: true,
                exportLoading: false,
                count: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    productionLineNameOrCode: '',
                    yearMonth: '',
                    workshopId: 22
                },
                dataItem: {},
                saveParams: {},
                bgColors: ['#19be6b', '#2d8cf0'],
                borderColors: ['#3fda8c', '#5cadff']
            };
        },
        mounted() {
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            this.$set(this.searchParams, 'workshopId', this.workshopList.find(x => x.name === '前纺区域') ? this.workshopList.find(x => x.name === '前纺区域').id : this.$store.state.user.userWorkshop.defaultWorkshopId);
            this.getDependentData();
        },
        methods: {
            tableRowClassName({ column }) {
                const item = this.lineConfig[column.property] || {};
                return {
                    background: item.bgColor,
                    border: `solid 0.5px ${item.borderColor}`,
                    color: item.bgColor ? '#fff' : '#515a6e'
                };
            },
            onFinishBtnOfFeedMaterial() {
                this.getListRequest();
                this.feedMaterialDialogState = false;
            },
            onAddBtn(e, key) {
                const workshopItem = this.workshopList.find(x => x.id === e.row.workshopId) || {};
                const productionLineItem = this.productionLineList.find(x => x.code === key) || {};
                this.saveParams = {
                    belongDate: e.row.belongDate,
                    workshopId: workshopItem.id,
                    workshopCode: workshopItem.code,
                    workshopName: workshopItem.name,
                    productionLineId: productionLineItem.id,
                    productionLineCode: productionLineItem.code,
                    productionLineName: productionLineItem.name
                };
                this.feedMaterialDialogState = true;
            },
            onVisibleChangeOfFeedMaterial(e) {
                this.feedMaterialDialogState = e;
                if (!e) {
                    this.saveParams = {};
                }
            },
            onDetailBtn(e, lineCode) {
                this.dataItem = {
                    lineCode,
                    belongDate: e.row.belongDate,
                    workshopId: e.row.workshopId
                };
                this.detailDialogState = true;
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.detailDialogState = e;
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getLineListRequest() {
                return ppfProductionLinePage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        let resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : [];
                        this.productionLineList = resData;
                        const processData = JSON.parse(JSON.stringify(this.processList));
                        let arr = [];
                        this.lineConfig = {};
                        let hasLine = false;
                        resData = resData.map(x => {
                            if (['3#', '4#', '5#'].includes(x.code)) {
                                arr = JSON.parse(JSON.stringify(processData)).filter(p => p.title !== '粗纱');
                            } else {
                                arr = JSON.parse(JSON.stringify(processData));
                            }
                            hasLine = !hasLine;
                            return {
                                key: x.code,
                                title: x.name,
                                children: arr.map(k => {
                                    const createKey = `${x.code}${k.key}`;
                                    if (this.lineConfig[createKey]) {
                                        this.lineConfig[createKey] = {
                                            key: createKey,
                                            bgColor: this.bgColors[hasLine ? 1 : 0],
                                            borderColor: this.borderColors[hasLine ? 1 : 0]
                                        };
                                    } else {
                                        this.lineConfig[createKey] = {
                                            key: createKey,
                                            bgColor: this.bgColors[hasLine ? 1 : 0],
                                            borderColor: this.borderColors[hasLine ? 1 : 0]
                                        };
                                    }
                                    return {
                                        key: createKey,
                                        title: k.title
                                    };
                                })
                            };
                        });
                        // resData.unshift({
                        //     key: 'belongDate',
                        //     title: '日期'
                        // });
                        this.tableHeader = resData;
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                this.$set(this.searchParams, 'yearMonth', formatMonth(Date.now()));
                await this.getLineListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 查询列表 */
            getListRequest() {
                if (this.searchParams.workshopId) {
                    this.tableLoading = true;
                    const params = { ...this.searchParams };
                    if (params.yearMonth) {
                        params.year = new Date(params.yearMonth).getFullYear();
                        params.month = new Date(params.yearMonth).getMonth() + 1;
                    }
                    return this.apiItem['page'](params).then(res => {
                        this.tableLoading = false;
                        this.count = res.data.count;
                        if (res.data.status === 200) {
                            if (res.data.res) {
                                // 后端暂时无法动态返回表头和表格数据,前端来拼接
                                this.tableData = res.data.res ? res.data.res.map(x => {
                                    this.tableHeader.forEach(columnItem => {
                                        if (x[columnItem.key] && columnItem.key !== 'belongDate') {
                                            for (const key in x[columnItem.key]) {
                                                x[`${columnItem.key}${key}`] = x[columnItem.key][key];
                                            }
                                        }
                                    });
                                    return x;
                                }) : [];
                            }
                        }

                        this.doLayoutTable();
                    });
                }
            },
            doLayoutTable() {
                this.$nextTick(() => {
                    this.$refs.jkTb.doLayout();
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.doLayoutTable();
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                this.getListRequest();
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            }
        }
    };
</script>
<style>
    .el-table .warning-row {
        background: oldlace;
    }

    .el-table .success-row {
        background: #f0f9eb;
    }
    .machine-group-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border-left: solid 1px #eee;
        border-top: solid 1px #eee;
        width: 80px;
        overflow: hidden;
        text-overflow: ellipsis;
        padding: 0 4px;
        flex-shrink: 0;
    }
</style>
